<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"
    />
    <title>作业批改</title>
    <link rel="stylesheet" type="text/css" href="../css/api.css" />
    <link rel="stylesheet" type="text/css" href="../css/style.css" />
    <link rel="stylesheet" type="text/css" href="../css/check.css" />
</head>

<body id="data-box">
    <div class="container">
        <div class="fn-left handle_menu_wrap">
            <div class="menu_title">
                工具
            </div>
            <div id="tools" class="handle_btn_list">
                <div class="handle_btn active" data-type="right">
                    <div class="handle_btn_img">
                        <img src="../image/check/all-true.png" class="center-self" alt="">
                    </div>
                    <div class="handle_btn_name">
                        全对
                    </div>
                </div>
                <div class="handle_btn" data-type="rectangle">
                    <div class="handle_btn_img">
                        <img src="../image/check/label-icon.png" class="center-self" alt="">
                    </div>
                    <div class="handle_btn_name">
                        错题标注
                    </div>
                </div>
                <div class="handle_btn" data-type="wrong">
                    <div class="handle_btn_img">
                        <img src="../image/check/all-wrong.png" class="center-self" alt="">
                    </div>
                    <div class="handle_btn_name">
                        全错
                    </div>
                </div>
                <div class="handle_btn" data-type="smallright">
                    <div class="handle_btn_img">
                        <img src="../image/check/true-icon.png" class="center-self" alt="">
                    </div>
                    <div class="handle_btn_name">
                        正确处
                    </div>
                </div>
                <div class="handle_btn" data-type="smallwrong">
                    <div class="handle_btn_img">
                        <img src="../image/check/wrong-icon.png" class="center-self" alt="">
                    </div>
                    <div class="handle_btn_name">
                        错误处
                    </div>
                </div>
                <div class="handle_btn" data-type="remove">
                    <div class="handle_btn_img">
                        <img src="../image/check/erasure-icon.png" class="center-self" alt="">
                    </div>
                    <div class="handle_btn_name">
                        擦除
                    </div>
                </div>
                <div class="handle_btn" data-type="help">
                    <div class="handle_btn_img">
                        <img src="../image/check/help-icon.png" class="center-self" alt="">
                    </div>
                    <div class="handle_btn_name">
                        帮助
                    </div>
                </div>
            </div>
        </div>
        <div class="fn-right correct_main">
            <div class="wrong_list_wrap">
                <div class="wrong_list_title">
                    <i class="before_icon fn-left"></i>
                    <div>错题</div>
                </div>
                <div class="wrong_list">
                    <div id="errMsg" class="wrong_list_inner">

                    </div>
                </div>
            </div>
            <div class="main_score">
                <div class="main_score_title">
                    <i class="before_icon fn-left"></i>
                    <div>字迹评分</div>
                </div>
                <div id="fontScore" class="main_score_num_list fn-clear">
                    <div class="main_score_num_item fn-left active">1</div>
                    <div class="main_score_num_item fn-left">2</div>
                    <div class="main_score_num_item fn-left">3</div>
                    <div class="main_score_num_item fn-left">4</div>
                    <div class="main_score_num_item fn-left">5</div>
                    <div class="main_score_num_item fn-left">6</div>
                    <div class="main_score_num_item fn-left">7</div>
                    <div class="main_score_num_item fn-left">8</div>
                    <div class="main_score_num_item fn-left">9</div>
                    <div class="main_score_num_item fn-left">10</div>
                </div>
            </div>
            <div id="subBut" class="small_btn_blue confirm">
                确认完成
            </div>
            <div id="moreBtn" class="more_btn"></div>
            <div id="moreDiv" class="other_btn_wrap fn-hide">
                <div id="expBtn" class="mark_exce">
                    异常标记
                </div>
                <div id="giveupBtn" class="give_up">
                    放弃任务
                </div>
            </div>
        </div>
        <div class="fn-right preview">
            <div id="simgDiv" class="swiper-container">

            </div>
            <div class="homework_total center-self-x">
                <span id="currentNum">1</span>/
                <span id="sumNum">1</span>
            </div>
        </div>
        <div class="view">
            <div id="canvasDiv" class="swiper-container center-self-x">
            </div>
        </div>
    </div>

    <div id="maskDiv" class="mask_modal" style="display: none;">
        <div class="top">
            <div style="width: 100%;padding-left: 30%;padding-top: 20%">数据提交中，请稍等...</div>
        </div>
    </div>


    <div id="errModal" class="mark_error_modal fn-hide">
        <div class="top"></div>
        <div class="mark_error_box center-self">
            <div class="mark_error_box_title">
                <div class="fn-left">
                    选择错误标签
                </div>
                <div id="hideModal" class="fn-right close_icon fn-clear fn-hide">
                    <img src="../image/check/close-icon.png" class="fn-left" alt="">
                </div>
            </div>
            <div id="errTags" class="wrong_label_list">

            </div>
            <div id="errVerify" class="small_btn_blue center-self-x confirm_mark">
                确认
            </div>
        </div>
    </div>
    <div id="testImg">

    </div>
</body>
<script type="text/javascript" src="../js/check/fontsize.js"></script>
<script type="text/javascript" src="../js/jquery.min.js"></script>
<script type="text/javascript" src="../js/check/qiniu.min.js"></script>
<script type="text/javascript" src="js/fabric.min.js"></script>
<script type="text/javascript" src="js/check/canvas.js"></script>
<script type="text/javascript" src="js/check/config.js"></script>
<script type="text/javascript" src="js/tools/md5.min.js"></script>
<script type="text/javascript" src="js/tools/uuid.js"></script>
<script type="text/javascript" src="js/tools/upload.js"></script>

<script type="text/javascript">
    jQuery(function () {
        var canvasInit = []; //已经初始化的canvas
        var uploadImageArray = []; //需要上传的图片集合{"name":"xxx","base64":"xxx"}
        var errTagType = {
            '语文': ['遗漏', '理解不清晰', '粗心大意', '审题不清', '基础不牢', '积累不够', '运用错误', '区分错误', '缺乏逻辑'],
            '数学': ['计算错误', '审题错误', '遗漏', '基础不牢固', '粗心大意', '概念不清', '换算错误', '公式不熟练', '缺乏解题技巧', '书写不端正'],
            '英语': ['粗心大意', '审题错误', '基础不牢固', '书写不规范', '单词拼写错误', '遗漏', '介词搭配错误', '单复数错误']
        };

        var img = decodeURIComponent(getUrlParam('img')); //图片集合
        var subject = decodeURIComponent(getUrlParam('subject')); //科目
        if (!img && JSON.parse(img)) {
            alert("网络错误");
        }
        img = JSON.parse(img);
        jQuery('#sumNum').text(img.length);
        var simgEle = "";
        for (var i = 0; i < img.length; i++) {
            if (i == 0) {
                jQuery("#canvasDiv").append('<canvas id="c0" height="1100" width="825"></canvas>');
                canvasInit.push("c0");
                switchCanvas(img[i].i, 0);
                simgEle += '<div class="swiper-slide swiper-slide-visible swiper-slide-active active-nav">';
            } else {
                simgEle += '<div class="swiper-slide swiper-slide-visible">';
            }
            simgEle += ('<div class="slide_inner"><img src="' + img[i].s + '" class="center-self"></div></div>');
        }
        jQuery("#simgDiv").append(simgEle);

        //点击缩略图
        jQuery(".swiper-slide-visible").on("click", function () {
            var _index = jQuery(this).index(),
                _cid = "c" + _index;
            if (canvasInit.indexOf(_cid) == -1) {
                jQuery("#canvasDiv").append('<canvas id="' + _cid + '" height="1100" width="825"></canvas>');
                canvasInit.push(_cid);
            }
            jQuery(this).addClass("active-nav").siblings().removeClass("active-nav");
            switchCanvas(img[_index].i, _index);
            jQuery("#currentNum").text(1 + _index);
        });

        //隐藏弹窗
        jQuery("#hideModal").on("click", function () {
            jQuery("#errModal").addClass("fn-hide");
        });

        //弹窗科目错误设置
        if (subject && errTagType[subject] && errTagType[subject].length > 0) {
            for (var i = 0; i < errTagType[subject].length; i++) {
                jQuery('#errTags').append('<div name="etag" class="wrong_label fn-left">' + errTagType[subject][i] + '</div>');
            }
        }

        //错误标签点击
        jQuery("div[name=etag]").on("click", function () {
            jQuery(this).toggleClass("active");
        });

        //错误标签选定
        jQuery("#errVerify").on("click", function () {
            var errTags = jQuery('#errTags').find(".active");
            if (errTags.length <= 0) {
                alert('请先选中标签！');
                return false;
            }
            var errSonEle = '<div class="wrong_item">';
            errSonEle += ' <i class="serial_number fn-left" value="' + appErrCount + '">' + appErrCount + '</i>';
            errSonEle += '<div class="wrong_content fn-clear">';
            for (var i = 0; i < errTags.length; i++) {
                errSonEle += '<div class="wrong_label fn-left">' + jQuery(errTags[i]).text() + '</div>';
            }
            errSonEle += '</div></div>';
            jQuery("#errMsg").prepend(errSonEle);
            jQuery("#errModal").addClass("fn-hide");
        });

        //绑定工具事件
        jQuery("#tools").find(".handle_btn").on("click", function () {
            //设置样式
            jQuery(this).addClass("active").siblings().removeClass("active");
            drawType = jQuery(this).attr("data-type");
            // window.drawType = drawType;
            canvas.isDrawingMode = false;
            if (drawType == "pen") {
                canvas.isDrawingMode = true;
            } else if (drawType == "remove") {
                canvas.selection = true;
                canvas.skipTargetFind = false;
                canvas.selectable = true;
            } else if (drawType == "help") {
                jQuery("#c").toggleClass("fn-hide");
            }
            else {
                canvas.skipTargetFind = true; //画板元素不能被选中
                canvas.selection = false; //画板不显示选中
            }
        });

        //get七牛token
        var qiniuToken = undefined;
        jQuery.ajax({
            type: "GET",
            cache: false,
            dataType: "jsonp",
            url: config.tokenURL,
            data: {},
            success: function (res) {
                qiniuToken = res.token;
            }
        });

        //提交作业
        jQuery("#subBut").on("click", function () {
            jQuery("#maskDiv").show();
            var fs = jQuery("#fontScore").find("div.active").index() + 1;
            if (fs <= 0) {
                alert("操作失败，请先选择字迹评分！");
                return false;
            }
            if (true) { //TODO:confirm("确认作业批改完成？")
                var checkJson = {
                    "pages": [],
                    "font": fs,
                    "callback": {
                        "task_id": (getUrlParam("task_id") || ""),
                        "task_list_id": (getUrlParam("task_list_id") || ""),
                        "userinfo": (getUrlParam("userinfo") || ""),
                        "type": (getUrlParam("type") || "")
                    }
                };
                window.checkJson = undefined;
                for (var i = 0; i < canvasArr.length; i++) {
                    if (canvasArr[i]) {
                        var canvasJson = {
                            "question": [],
                            "page": {
                                "img": "",
                                "imgorg": "",
                                "w": 0,
                                "h": 0,
                                "index": i
                            }
                        };
                        var objs = canvasArr[i].getObjects();
                        var checkObj = [];
                        for (var j = 0; j < objs.length; j++) {
                            if (objs[j].type && objs[j].type != 'image') {
                                checkObj.push(objs[j]);
                            } else {
                                var _imgName = md5(uuid.uuid() + new Date().getTime()) + ".png";
                                canvasJson.page.imgorg = objs[j]._element.src;
                                canvasJson.page.img = config.imgDomain + _imgName;
                                canvasJson.page.w = objs[j].width;
                                canvasJson.page.h = objs[j].height;
                                addUploadImg(canvasArr[i], objs[j], _imgName, false);
                            }
                        }

                        checkObj.sort(function (x, y) { return x.top - y.top; }); //根据控件top排序

                        var itemSmallRight = 0, itemSmallWrong = 0, prevSmallType = true, errImg = "", errIndexs = [];
                        for (var j = 0; j < checkObj.length; j++) {
                            switch (checkObj[j].type) {
                                case 'smallright':
                                    ++itemSmallRight;
                                    errIndexs.push(checkObj[j].eindex);
                                    break;
                                case 'smallwrong':
                                    ++itemSmallWrong;
                                    errIndexs.push(checkObj[j].eindex);
                                    break;
                                case 'right':
                                case 'wrong':
                                    prevSmallType = false;
                                    break;
                                case 'rectangle': //框
                                    var _imgName = md5(uuid.uuid() + new Date().getTime()) + ".png";
                                    errImg = config.imgDomain + _imgName;
                                    addUploadImg(canvasArr[i], checkObj[j], _imgName, true);
                                    prevSmallType = false;
                                    break;
                                default:
                                    break;
                            }
                            if (prevSmallType == false || j == (checkObj.length - 1)) {
                                //下一题为整题对/错 || 最后一题 （结算上一题[小错/对]）
                                if (itemSmallRight > 0 || itemSmallWrong > 0) {
                                    var errJson = [];
                                    if (errIndexs.length > 0) {
                                        for (var m = 0; m < errIndexs.length; m++) {
                                            var _eindex = errIndexs[m];
                                            var txt = getErrTagsByIndex(_eindex);
                                            errJson.push({
                                                "id": _eindex + 1,
                                                "desc": txt,
                                                "x": checkObj[m].left,
                                                "y": checkObj[m].top
                                            });
                                        }
                                    }
                                    canvasJson.question.push({ 'r': 0, 'w': 0, 'sr': itemSmallRight, 'sw': itemSmallWrong, 'eimg': errImg, 'err': errJson });
                                    errImg = "";
                                    errIndexs = [];
                                    itemSmallRight = 0, itemSmallWrong = 0;
                                }
                                prevSmallType = true;
                            }
                            //录入本次大题
                            if (checkObj[j].type == 'right') {
                                canvasJson.question.push({ 'r': 1, 'w': 0, 'sr': 0, 'sw': 0, 'eimg': '', 'err': [] });
                            } else if (checkObj[j].type == 'wrong') {
                                var errJson = [];
                                var _eindex = checkObj[j].eindex;
                                var txt = getErrTagsByIndex(_eindex);
                                errJson[0] = {
                                    "id": _eindex + 1,
                                    "desc": txt,
                                    "x": checkObj[j].left,
                                    "y": checkObj[j].top
                                };
                                canvasJson.question.push({ 'r': 0, 'w': 1, 'sr': 0, 'sw': 0, 'eimg': errImg, 'err': errJson });
                                errImg = "";
                            }
                        }
                        checkJson.pages.push(canvasJson);
                    } else {
                        //这里的图片没有点击初始化
                    }
                }
                window.checkJson = JSON.stringify(checkJson);

                //上传图片+请求服务器
                uploadImg(uploadImageArray, qiniuToken);
            }
        });
        //更多操作
        jQuery("#moreBtn").on("click", function () {
            jQuery("#moreDiv").toggleClass("fn-hide");
        });
        //异常订单
        jQuery("#expBtn").on("click", function () {
            jQuery("#moreDiv").toggleClass("fn-hide");
            if (confirm("确认为异常订单？")) {
                //TODO:业务
            }
        });
        //放弃订单
        jQuery("#giveupBtn").on("click", function () {
            jQuery("#moreDiv").toggleClass("fn-hide");
            if (confirm("确认为放弃订单？")) {
                //TODO:业务
            }
        });
        //字体打分
        jQuery("#fontScore").find("div").on("click", function () {
            jQuery(this).addClass("active").siblings().removeClass("active");

        });
        //获取url中的参数
        function getUrlParam(name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return decodeURI(r[2]);
            return null;
        }
        //添加上传图片 （isRemove：类型bool，是否需要移除截图在添加）
        function addUploadImg(canvas, canvasControl, imgName, isRemove) {
            if (isRemove) {
                canvas.remove(canvasControl);
            }
            var base64 = canvas.toDataURL({
                format: 'png',
                left: canvasControl.left,
                top: canvasControl.top,
                width: canvasControl.width,
                height: canvasControl.height
            });

            uploadImageArray.push({ "name": imgName, "base64": base64 });

            // jQuery("#testImg").append('<img src="' + base64 + '"/><br />');

            if (isRemove) {
                canvas.add(canvasControl);
            }
        }
        //获取错误标签描述集合（根据标号）
        function getErrTagsByIndex(eindex) {
            var txt = "";
            var txtCt = jQuery('#errMsg').find('.wrong_item > i[value="' + (eindex + 1) + '"]').siblings().find('div');
            for (var k = 0; k < txtCt.length; k++) {
                txt += txtCt.eq(k).text();

                if (k != (txtCt.length - 1)) {
                    txt += ",";
                }
            }
            return txt;
        }

    });




</script>

</html>